<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item   label="门店名称" prop="storeId">
        <treeselect
          :defaultExpandLevel=1
          v-model="queryParams.storeId"
          :options="storeOptions"
          :normalizer="normalizer"
          placeholder="请输入或选择门店名称"
          style="width: 350px"/>
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="payState">
        <el-select v-model="queryParams.payState" placeholder="请选择支付状态" clearable size="small">
          <el-option
            v-for="dict in payStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付记录单号" prop="payOrderNo">
        <el-input
          v-model="queryParams.payOrderNo"
          placeholder="请输入支付记录单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="支付方式" prop="payType">-->
<!--        <el-select v-model="queryParams.payType" placeholder="请选择支付方式" clearable size="small">-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="订单状态" prop="orderState">
        <el-select v-model="queryParams.orderState" placeholder="请选择订单状态" clearable size="small">
          <el-option
            v-for="dict in orderStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退款状态" prop="refundStatus">
        <el-select v-model="queryParams.refundStatus" placeholder="请选择退款状态" clearable size="small">
          <el-option
            v-for="dict in refundStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退款订单号" prop="refundPayOrderNo">
        <el-input
          v-model="queryParams.refundPayOrderNo"
          placeholder="请输入退款订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退款支付状态" prop="refundPayStatus">
        <el-select v-model="queryParams.refundPayStatus" placeholder="请选择退款支付状态" clearable size="small">
          <el-option
            v-for="dict in refundPayStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退款时间" prop="refundTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.refundTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择退款时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结算状态" prop="billingState">
        <el-select v-model="queryParams.billingState" placeholder="请选择结算状态" clearable size="small">
          <el-option
            v-for="dict in billingStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
          v-if="false"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :height="tableHeight" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column label="主键" align="center" prop="id" v-if="false"/>
      <el-table-column label="订单号" align="center" prop="orderId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="门店名称" align="center" prop="storeName" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
      <el-table-column label="实际支付金额" align="center" prop="payPrice" />
      <el-table-column label="抵扣金额" align="center" prop="deductionPrice" />
      <el-table-column label="优惠券金额" align="center" prop="couponPrice" />
      <el-table-column label="支付状态" align="center" prop="payState">
        <template slot-scope="scope">
          <dict-tag :options="payStateOptions" :value="scope.row.payState"/>
        </template>
      </el-table-column>
      <el-table-column label="支付记录单号" align="center" prop="payOrderNo" show-overflow-tooltip/>
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderState">
        <template slot-scope="scope">
          <p v-if="scope.row.orderState == 'refund_apply' && scope.row.refundStatus == 'refused'">拒绝退款</p>
          <dict-tag v-else :options="orderStateOptions" :value="scope.row.orderState"/>
        </template>
      </el-table-column>
      <el-table-column label="核销码" align="center" prop="verifyCode" />
<!--      <el-table-column label="核销人名称" align="center" prop="storeUserName" />-->
      <el-table-column label="核销时间" align="center" prop="verifyCodeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.verifyCodeTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="抽佣比例" align="center" prop="commissionPercent" />
      <el-table-column label="商家金额" align="center" prop="storeMoney" />
      <el-table-column label="平台金额" align="center" prop="platformMoney" /> -->
      <el-table-column label="门店金额" align="center" prop="storeprice" />
      <el-table-column label="分销金额" align="center" prop="fenxiaoprice" />
      <!-- <el-table-column label="佣金金额" align="center" prop="yongjinprice" /> -->
      <el-table-column label="结算状态" align="center" prop="billingState">
        <template slot-scope="scope">
          <dict-tag :options="billingStateOptions" :value="scope.row.billingState"/>
        </template>
      </el-table-column>
      <el-table-column label="结算时间" align="center" prop="billingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.billingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款状态" align="center" prop="refundStatus">
        <template slot-scope="scope">
          <dict-tag :options="refundStatusOptions" :value="scope.row.refundStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="退款订单号" align="center" prop="refundPayOrderNo" />
      <el-table-column label="退款支付状态" align="center" prop="refundPayStatus" />
      <el-table-column label="退款支付失败原因" align="center" prop="refundPayErrMsg" />
      <el-table-column label="退款原因" align="center" prop="refundReason" />
      <el-table-column label="退款时间" align="center" prop="refundTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.refundTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center" prop="refundPrice" />
      <el-table-column label="拒绝退款原因" align="center" prop="refundRefuseReason" />
      <el-table-column
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" v-if="scope.row.refundStatus == 'apply'" @click="handleAudit(2,scope.row.id)" >通过</el-button>
          <el-button type="text" size="small" v-if="scope.row.refundStatus == 'apply'" @click="handleAudit(1,scope.row.id)" >驳回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总价" />
        </el-form-item>
        <el-form-item label="实际支付金额" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入实际支付金额" />
        </el-form-item>
        <el-form-item label="抵扣金额" prop="deductionPrice">
          <el-input v-model="form.deductionPrice" placeholder="请输入抵扣金额" />
        </el-form-item>
        <el-form-item label="优惠券金额" prop="couponPrice">
          <el-input v-model="form.couponPrice" placeholder="请输入优惠券金额" />
        </el-form-item>
        <el-form-item label="支付状态">
          <el-radio-group v-model="form.payState">
            <el-radio
              v-for="dict in payStateOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付记录单号" prop="payOrderNo">
          <el-input v-model="form.payOrderNo" placeholder="请输入支付记录单号" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable size="small"
            v-model="form.payTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-radio-group v-model="form.orderState">
            <el-radio
              v-for="dict in orderStateOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款状态">
          <el-radio-group v-model="form.refundStatus">
            <el-radio
              v-for="dict in refundStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款订单号" prop="refundPayOrderNo">
          <el-input v-model="form.refundPayOrderNo" placeholder="请输入退款订单号" />
        </el-form-item>
        <el-form-item label="退款支付状态">
          <el-radio-group v-model="form.refundPayStatus">
            <el-radio
              v-for="dict in refundPayStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款支付失败原因" prop="refundPayErrMsg">
          <el-input v-model="form.refundPayErrMsg" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input v-model="form.refundReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="退款时间" prop="refundTime">
          <el-date-picker clearable size="small"
            v-model="form.refundTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择退款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="退款金额" prop="refundPrice">
          <el-input v-model="form.refundPrice" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="拒绝退款原因" prop="refundRefuseReason">
          <el-input v-model="form.refundRefuseReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="核销码" prop="verifyCode">
          <el-input v-model="form.verifyCode" placeholder="请输入核销码" />
        </el-form-item>
        <el-form-item label="核销人名称" prop="storeUserName">
          <el-input v-model="form.storeUserName" placeholder="请输入核销人名称" />
        </el-form-item>
        <el-form-item label="核销时间" prop="verifyCodeTime">
          <el-date-picker clearable size="small"
            v-model="form.verifyCodeTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择核销时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="抽佣比例" prop="commissionPercent">
          <el-input v-model="form.commissionPercent" placeholder="请输入抽佣比例" />
        </el-form-item>
        <el-form-item label="商家金额" prop="storeMoney">
          <el-input v-model="form.storeMoney" placeholder="请输入商家金额" />
        </el-form-item>
        <el-form-item label="平台金额" prop="platformMoney">
          <el-input v-model="form.platformMoney" placeholder="请输入平台金额" />
        </el-form-item>
        <el-form-item label="结算状态">
          <el-radio-group v-model="form.billingState">
            <el-radio
              v-for="dict in billingStateOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="结算时间" prop="billingTime">
          <el-date-picker clearable size="small"
            v-model="form.billingTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结算时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 退款 -->
    <el-dialog
      title="退款审核"
      :visible.sync="auditvisible"
      width="600px"
      @close="auditclose"
      >
      <div v-if="audittype == 1">
        <p>拒绝退款</p>
        <el-input type="textarea" placeholder="退款理由" v-model="reason" ></el-input>
      </div>
      <div v-if="audittype == 2">
        <p>退款金额</p>
        <el-input type="text" v-model="refundPrice" ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="auditcancel">取 消</el-button>
        <el-button type="primary" @click="auditsubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, logicDelOrder, addOrder, updateOrder, exportOrder,refuseRefund,passRefund } from "@/api/order/order";
import { storeListParam } from "@/api/store/store";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Order",
  components:{Treeselect},
  data() {
    return {
      tableHeight:0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 订单信息表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 支付状态字典
      payStateOptions: [],
      // 订单状态字典
      orderStateOptions: [],
      // 退款状态字典
      refundStatusOptions: [],
      refundPayStatusOptions: [],
      // 结算状态字典
      billingStateOptions: [],
      storeOptions:[],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        storeId: null,
        productId: null,
        productName: null,
        productBackId: null,
        memberId: null,
        totalPrice: null,
        payPrice: null,
        deductionPrice: null,
        couponId: null,
        couponPrice: null,
        payState: null,
        payOrderNo: null,
        payTime: null,
        payType: null,
        orderState: null,
        refundStatus: null,
        refundPayOrderNo: null,
        refundPayStatus: null,
        refundPayErrMsg: null,
        refundReason: null,
        refundTime: null,
        refundPrice: null,
        refundRefuseReason: null,
        verifyCode: null,
        storeUserId: null,
        storeUserName: null,
        verifyCodeTime: null,
        commissionPercent: null,
        storeMoney: null,
        platformMoney: null,
        billingState: null,
        billingTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      reason: '',
      auditvisible: false,
      auditid: '',
      refundPrice: ''
    };
  },
  created() {
    this.getList();
    this.calHeight()
      this.getDicts("sys_yes_no").then(response => {
      this.payStateOptions = response.data;
    });
    this.getDicts("order_state").then(response => {
      this.orderStateOptions = response.data;
    });
    this.getDicts("refund_status").then(response => {
      this.refundStatusOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.refundPayStatusOptions = response.data;
    });
    this.getDicts("billing_state").then(response => {
      this.billingStateOptions = response.data;
    });
    storeListParam().then(res =>{
      this.storeOptions = res
    })
  },
  watch: {
    'showSearch':'calHeight'
  },
  methods: {
    normalizer(node) {
      return {
        id: node.dictValue,
        label: node.dictLabel,
      };
    },
    calHeight () {
          this.$nextTick(() => {
              const rect = this.$refs.appcontainer.getBoundingClientRect();
              let height= this.$refs.queryForm.$el.offsetHeight;
              this.tableHeight = rect.height-height-120;
          })
      },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      listOrder(this.addDateRange(this.queryParams, this.dateRange,'PayTime')).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        storeId: null,
        productId: null,
        productName: null,
        productBackId: null,
        memberId: null,
        totalPrice: null,
        payPrice: null,
        deductionPrice: null,
        couponId: null,
        couponPrice: null,
        payState: "0",
        payOrderNo: null,
        payTime: null,
        payType: null,
        orderState: "0",
        refundStatus: "0",
        refundPayOrderNo: null,
        refundPayStatus: "0",
        refundPayErrMsg: null,
        refundReason: null,
        refundTime: null,
        refundPrice: null,
        refundRefuseReason: null,
        verifyCode: null,
        storeUserId: null,
        storeUserName: null,
        verifyCodeTime: null,
        commissionPercent: null,
        storeMoney: null,
        platformMoney: null,
        billingState: "0",
        delState: null,
        delUser: null,
        billingTime: null,
        delType: null,
        delTime: null,
        createBy: null,
        createType: null,
        createTime: null,
        updateBy: null,
        updateType: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.showSearch=false;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 售后按钮操作 */
    handleAfter(row) {
      const ids = row.id || this.ids;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return logicDelOrder(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有订单信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    auditclose() {
      this.reason = ''
    },
    auditcancel() {
      this.auditvisible = false
      this.auditclose()
    },
    handleAudit(type,id) {
      this.auditid = id
      this.audittype = type
      this.auditvisible = true
    },
    auditsubmit() {
      if(this.audittype == 1) {
        const data = {
          reason: this.reason
        }
        refuseRefund(data,this.auditid).then(res => {
          if(res.success) {
              this.$message({
                message: '审核成功',
                type: 'success'
              });
            this.auditvisible = false
            this.getList()
          } else {
            this.$message({
                message: '审核失败',
                type: 'warning'
            });
          }

        })
      }
      if(this.audittype == 2) {
        const data = {
          refundPrice: this.refundPrice,
          orderId: String(this.auditid)
        }
        passRefund(data).then(res => {
          if(res.success) {
            this.$message({
              message: '审核成功',
              type: 'success'
            });
            this.auditvisible = false
            this.getList()
          } else {
            this.$message({
              message: res.msg,
              type: 'warning'
            })
          }

        })
      }
    }
  }
};
</script>
